package de.upb.messerschmidt.set;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import de.upb.messerschmidt.set.entity.Location;
import de.upb.messerschmidt.set.entity.Room;
import de.upb.messerschmidt.set.jdo.PMF;

/**
 * Gets a {@link Room}'s data via an HttpPost and persists it.
 * 
 * @author Tim Messerschmidt
 * 
 */
public class RegisterRoomServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String locationName = req.getParameter("location");
		String identifier = req.getParameter("identifier");

		if (locationName == null || identifier == null) {
			resp.setStatus(400);
			resp.getWriter().println("Please fill in all fields");
		} else {
			PersistenceManager pm = PMF.get().getPersistenceManager();

			Query query = pm.newQuery(Location.class);
			query.setFilter("name == nameParam");
			query.declareParameters("String nameParam");
			query.setOrdering("name desc");

			Location location;

			List<Location> results = (List<Location>) query
					.execute(locationName);

			if (!results.isEmpty()) {
				location = results.get(0);

				Room room = new Room(identifier, location);
				location.getRooms().add(room);

				try {
					pm.refresh(location);

					resp.setStatus(200);
					resp.getWriter().println("Registration successfull");
				} catch (Exception e) {
					e.printStackTrace();
					resp.setStatus(400);
					resp.getWriter().println("Registration failed: " + e);
				} finally {
					pm.close();
				}
			} else {
				resp.setStatus(400);
				resp.getWriter().println("No matching location found!");
			}
		}
	}
}
